package com.nvwa.mvp.abase.appender;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.encoder.Encoder;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import lombok.Setter;
import lombok.SneakyThrows;

import java.io.File;
import java.io.FileOutputStream;

/**
 * 自定义附加器
 */
@Setter
public class MyAppender<E> extends UnsynchronizedAppenderBase<E> {
    private Encoder encoder;
    private String filename;
    @SneakyThrows
    @Override
    protected void append(E e) {
        ILoggingEvent event = (ILoggingEvent) e;
        byte[] bStr = this.encoder.encode(event);
        String log = new String(bStr, "utf-8");
        System.out.println(log);//将日志输出到控制台

        //将日志输出到文件
        File file = new File(filename);
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(file, true);
        fos.write(log.getBytes());
        fos.close();
    }
}
